import {
	Card,
	CardContent,
	Grid,
	IconButton,
	Skeleton,
	Tooltip
} from '@mui/material'
import { useQuery } from '@tanstack/react-query'
import { Plus } from 'lucide-react'
import { useRouter } from 'next/navigation'

import { TaskMinCard } from '@/components/cards/min/task.min.card'

import type { ITask } from '@/types/task.types'

import { DASHBOARD_PAGES } from '@/config/pages-url.config'

import { taskService } from '@/services/tasks.service'

export function TasksGallery({
	for_object
}: {
	for_object: {
		id: number
		name:
			| 'request'
			| 'contract'
			| 'warranty'
			| 'reclamation'
			| 'delivery'
			| 'assembly'
			| 'worker'
		count: number
	}
}) {
	const router = useRouter()
	const {
		data: tasks,
		isLoading,
		isRefetching
	} = useQuery<ITask[]>({
		queryKey: ['tasks_for', for_object.name, for_object.id],
		queryFn: async () =>
			await taskService.fetchMany(for_object).then(res => res.results),
		enabled: for_object.count > 0
	})

	return (
		<Grid
			container
			direction='row'
			sx={{
				overflowX: 'auto',
				width: '100%',
				flexWrap: 'nowrap',
				marginBottom: 2,
				alignItems: 'stretch'
			}}
			spacing={2}
		>
			{isLoading || isRefetching ? (
				<>
					<Grid item>
						<Skeleton
							width={300}
							height={300}
						/>
					</Grid>
					<Grid item>
						<Skeleton
							width={300}
							height={300}
						/>
					</Grid>
					<Grid item>
						<Skeleton
							width={300}
							height={300}
						/>
					</Grid>
				</>
			) : (
				<>
					{tasks &&
						tasks?.map(task => (
							<Grid
								item
								key={task.id}
							>
								<TaskMinCard
									task={task}
									queryKey={['tasks_for', for_object.name, for_object.id]}
								/>
							</Grid>
						))}
					<Grid
						item
						sx={{
							alignSelf: 'center'
						}}
					>
						<Card>
							<CardContent
								sx={{
									display: 'flex',
									flexDirection: 'column',
									alignItems: 'center',
									justifyContent: 'center',
									padding: 4
								}}
							>
								<Tooltip
									title='Добавить задачу'
									placement='top'
								>
									<IconButton
										color='success'
										size={'large'}
										onClick={() =>
											router.push(
												`${DASHBOARD_PAGES.TASK_NEW}?for=${for_object.name}&id=${for_object.id}`
											)
										}
									>
										<Plus size={30} />
									</IconButton>
								</Tooltip>
							</CardContent>
						</Card>
					</Grid>
				</>
			)}
		</Grid>
	)
}
